package com.dalitek.sampleface;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.dalitek.sampleface.adapter.FaceQueryAdapter;
import com.dalitek.sampleface.view.CameraDetectView;
import com.dalitek.sampleface.view.OverlayEntity;
import com.oliveapp.face.libfacecapture.x.XFace;
import com.oliveapp.face.libfacecapture.x.entity.Face;
import com.oliveapp.face.libfacecapture.x.entity.FaceEntity;
import com.oliveapp.face.libfacecapture.x.entity.WatchDogEvent;
import com.oliveapp.face.libfacecapture.x.interfaces.CaptureListener;
import com.oliveapp.face.libfacecapture.x.interfaces.FaceAccessListener;
import com.oliveapp.face.libfacecapture.x.interfaces.InitListener;
import com.oliveapp.face.libfacecapture.x.interfaces.WatchDogListener;
import com.oliveapp.libcommon.utility.FileUtil;
import com.oliveapp.libcommon.utility.LogUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.oliveapp.face.libfacecapture.captor.SessionStatusEnum.SESSION_PASS;
import static com.oliveapp.face.libfacecapture.captor.SessionStatusEnum.SESSION_SINGLE_FRAME_OK;
import static com.oliveapp.face.libfacecapture.datatype.LibFaceCaptureParameters.IMG_PATH;
import static com.oliveapp.libcommon.datatype.ErrorCode.ERROR_PROCESSING;
import static com.oliveapp.libcommon.datatype.ErrorCode.ERROR_SUCCESS;
import static com.oliveapp.libcommon.datatype.ErrorCode.ERROR_SUCCESS_CAMERA;
import static com.oliveapp.libcommon.utility.LogUtil.VERBOSE;

public class _1VNActivity extends BaseActivity implements CaptureListener, InitListener, FaceAccessListener, WatchDogListener {
    private static final String TAG = _1VNActivity.class.getSimpleName();
    private ArrayList<Object> requestPermissions;
    private static final int REQUEST_CODE = 1;
    private View overlayView;

    private static final int VIDEO_WIDTH = captureConfig_1vn.getVideo_width();
    private static final int VIDEO_HEIGHT = captureConfig_1vn.getVideo_height();

    private static final int PAINT_COLOR_FACE = Color.RED;
    private static final int PAINT_COLOR_FACE_PASS = Color.WHITE;

    private TextView tvTitle,tvResult;
    private XFace xFace;
    private AlertDialog addDialog;
    private View btnRegister;
    private View btnQuery;
    private View btnSetting;
    private Handler faceQueryHandler =new Handler();
    private Runnable faceQueryRunnable = () -> {tvResult.setText("");};
    private TextView tvInit;

    private FrameLayout fr_camera;
    private int width;
    private int height;

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //打开LOG打印等级
        LogUtil.MIN_LOG_LEVEL = VERBOSE;
        LogUtil.ENABLE_LOG = true;
        LogUtil.e(TAG, "onCreate");

        //设置全屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);
        Display mDisplay = getWindowManager().getDefaultDisplay();
        width = mDisplay.getWidth();
        height = mDisplay.getHeight();
        height = width * VIDEO_WIDTH / VIDEO_HEIGHT;

        initView();
        initEvent();
        startUp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(xFace!=null){
            xFace.unInit();
            xFace = null;
        }
    }

    private void initView() {
        overlayView = findViewById(R.id.back_view);
        tvTitle = findViewById(R.id.tv_title);
        tvInit = findViewById(R.id.tv_init);
        tvResult = findViewById(R.id.tv_result);
        btnRegister = findViewById(R.id.btn_register);
        btnQuery = findViewById(R.id.btn_query);
        btnSetting = findViewById(R.id.btn_setting);
        fr_camera = findViewById(R.id.fr_camera);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,height);
        fr_camera.setLayoutParams(layoutParams);
    }

    private void initEvent() {
        findViewById(R.id.btn_back).setOnClickListener(view -> {
            xFace.closeCamera();
           startActivity(new Intent(bContext,LaunchActivity.class));
            finish();
        });
        final int[] tmpFaceRectScaleX = {captureConfig_1vn.getScaleX()};
        final boolean[] tmpNeedAutoFocus = {captureConfig_1vn.isNeedAutoFocus()};
        btnSetting.setOnClickListener(view -> {
            dismissLoadingDialog();
            if( addDialog!=null && addDialog.isShowing()) addDialog.dismiss();
            addDialog = new AlertDialog.Builder(this)
                    .setNegativeButton("取消", (dialogInterface, i) -> {
                        dismissLoadingDialog();
                        addDialog.dismiss();
                    }).create();
            ScrollView scrollView = (ScrollView) LayoutInflater.from(bContext).inflate(R.layout.dialog_setting,null);

            //设置激活License
            scrollView.findViewById(R.id.btn_activate_license).setOnClickListener(view15 -> xFace.activateLicense((rtn, message) -> {
                toast(message);
            }));

            //设置验证License激活状态
            scrollView.findViewById(R.id.btn_verify_license).setOnClickListener(view14 -> {
                toast(xFace.verifyLicense()?"已激活":"未激活");
            });

            //设置重置清除License
            scrollView.findViewById(R.id.btn_clear_license).setOnClickListener(view1 -> {
                xFace.clearLicense();
                toast("清除License成功!");
            });

            //设置重置人脸抓拍算法
            scrollView.findViewById(R.id.btn_reset_captor).setOnClickListener(view12 -> {
                xFace.reInitCaptor();
                addDialog.dismiss();
            });

            //设置重置人脸对比算法
            scrollView.findViewById(R.id.btn_reset_verify).setOnClickListener(view13 -> {
                xFace.reInitVerify();
                addDialog.dismiss();
            });

            //设置跳转至三方Activity
            scrollView.findViewById(R.id.btn_test).setOnClickListener(view6 -> {
                startActivity(new Intent(bContext,TestActivity.class));
                addDialog.dismiss();
            });

            //人脸识别阈值设置
            Spinner verifyThresholdSpinner = scrollView.findViewById(R.id.sp_verify_threshold);
            String[] verifyThresholds =  {"10","20","40","80","90"};//范围0~100连续值
            verifyThresholdSpinner.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, verifyThresholds));
            verifyThresholdSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    if(i!=getIntArrayPosition(verifyThresholds, xFace.getThreshold())){
                        xFace.setThreshold(Integer.parseInt(verifyThresholds[i]));
                        addDialog.dismiss();
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
            verifyThresholdSpinner.setSelection(getIntArrayPosition(verifyThresholds, xFace.getThreshold()));


            //设置打开活体
            scrollView.findViewById(R.id.btn_live_open).setOnClickListener(view16 -> {
                xFace.setUseDualCamera(true);
                xFace.setHideSurfaceInfrared(false);
                xFace.reInitCaptor();
                addDialog.dismiss();
            });

            //设置关闭活体
            scrollView.findViewById(R.id.btn_live_close).setOnClickListener(view16 -> {
                xFace.setUseDualCamera(false);
                xFace.setHideSurfaceInfrared(true);
                xFace.reInitCaptor();
                addDialog.dismiss();
            });

            //设置活体等级，单目模式默认零级，设置无效
            Spinner liveLevelSpinner = scrollView.findViewById(R.id.sp_live_level);
            String[] liveLevels = {"零级","一级","二级","三级"};
            liveLevelSpinner.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, liveLevels));
            liveLevelSpinner.setSelection(xFace.getCaptureSecureLevel());
            liveLevelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    if(i!=xFace.getCaptureSecureLevel()){
                        xFace.setCaptureSecureLevel(i);
                        xFace.reInitCaptor();
                        addDialog.dismiss();
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });

            //人像抓拍占镜头最小比率 可根据此设置制作识别距离控制逻辑
            Spinner faceRatioMinSpinner = scrollView.findViewById(R.id.sp_face_ratio_min);
            String[] faceRatioMins =  {"0","0.3","0.5","0.7","1.0"};//范围0~1连续值
            faceRatioMinSpinner.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, faceRatioMins));
            faceRatioMinSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    if(i!=getDoubleArrayPosition(faceRatioMins, xFace.getMinFaceRatio())){
                        xFace.setMinFaceRatio(Double.parseDouble(faceRatioMins[i]));
                        xFace.reInitCaptor();
                        addDialog.dismiss();
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
            faceRatioMinSpinner.setSelection(getDoubleArrayPosition(faceRatioMins, xFace.getMinFaceRatio()));

            //设置相机旋转角度
            RadioGroup rgCameraDegree = scrollView.findViewById(R.id.rg_camera_degree);
            switch (xFace.getCameraDegree()){
                case 0 :
                    rgCameraDegree.check(R.id.rb_camera_degree_0);
                    break;
                case 90 :
                    rgCameraDegree.check(R.id.rb_camera_degree_90);
                    break;
                case 180 :
                    rgCameraDegree.check(R.id.rb_camera_degree_180);
                    break;
                case 270 :
                    rgCameraDegree.check(R.id.rb_camera_degree_270);
                    break;
            }
            rgCameraDegree.setOnCheckedChangeListener((radioGroup, i) -> {
                switch (i){
                    case R.id.rb_camera_degree_0:
                        xFace.setCameraDegree(0);
                        break;
                    case R.id.rb_camera_degree_90:
                        xFace.setCameraDegree(90);
                        break;
                    case R.id.rb_camera_degree_180:
                        xFace.setCameraDegree(180);
                        break;
                    case R.id.rb_camera_degree_270:
                        xFace.setCameraDegree(270);
                        break;
                }
                xFace.reInitCaptor();
                addDialog.dismiss();
            });

            //设置帧数据旋转角度
            RadioGroup rgFrameDataDegree = scrollView.findViewById(R.id.rg_frame_data_degree);
            switch (xFace.getFrameDataDegree()){
                case 0 :
                    rgFrameDataDegree.check(R.id.rb_frame_data_degree_0);
                    break;
                case 90 :
                    rgFrameDataDegree.check(R.id.rb_frame_data_degree_90);
                    break;
                case 180 :
                    rgFrameDataDegree.check(R.id.rb_frame_data_degree_180);
                    break;
                case 270 :
                    rgFrameDataDegree.check(R.id.rb_frame_data_degree_270);
                    break;
            }
            rgFrameDataDegree.setOnCheckedChangeListener((radioGroup, i) -> {
                switch (i){
                    case R.id.rb_frame_data_degree_0:
                        xFace.setFrameDataDegree(0);
                        break;
                    case R.id.rb_frame_data_degree_90:
                        xFace.setFrameDataDegree(90);
                        break;
                    case R.id.rb_frame_data_degree_180:
                        xFace.setFrameDataDegree(180);
                        break;
                    case R.id.rb_frame_data_degree_270:
                        xFace.setFrameDataDegree(270);
                        break;
                }
                xFace.reInitCaptor();
                addDialog.dismiss();
            });

            //人脸框镜像开启
            CheckBox cbFaceRectScaleX = scrollView.findViewById(R.id.cb_face_rect_scale_x);
            cbFaceRectScaleX.setChecked( tmpFaceRectScaleX[0] == -1);
            cbFaceRectScaleX.setOnCheckedChangeListener((compoundButton, b) -> {
                tmpFaceRectScaleX[0] = b?-1:1;
                ((CameraDetectView)overlayView).init(VIDEO_WIDTH, VIDEO_HEIGHT,height,width,tmpFaceRectScaleX[0]);
                addDialog.dismiss();
            });

            //自动对焦启用(变焦摄像头有效)
            CheckBox cbNeedAutoFocus = scrollView.findViewById(R.id.cb_need_auto_focus);
            cbNeedAutoFocus.setChecked(tmpNeedAutoFocus[0]);
            cbNeedAutoFocus.setOnCheckedChangeListener((compoundButton, b) -> {
                tmpNeedAutoFocus[0] = b;
                xFace.setNeedAutoFocus(b);
                xFace.reInitCaptor();
                addDialog.dismiss();
            });

            //设置可见光摄像头id
            RadioGroup rgCameraVisible = scrollView.findViewById(R.id.rg_camera_visible);
            switch (xFace.getVisibleCameraId()){
                case 0 :
                    rgCameraVisible.check(R.id.rb_camera_visible_0);
                    break;
                case 1 :
                    rgCameraVisible.check(R.id.rb_camera_visible_1);
                    break;
                case 2 :
                    rgCameraVisible.check(R.id.rb_camera_visible_2);
                    break;
                case 3 :
                    rgCameraVisible.check(R.id.rb_camera_visible_3);
                    break;
            }
            rgCameraVisible.setOnCheckedChangeListener((radioGroup, i) -> {
                switch (i){
                    case R.id.rb_camera_visible_0:
                        xFace.setVisibleCameraId(0);
                        break;
                    case R.id.rb_camera_visible_1:
                        xFace.setVisibleCameraId(1);
                        break;
                    case R.id.rb_camera_visible_2:
                        xFace.setVisibleCameraId(2);
                        break;
                    case R.id.rb_camera_visible_3:
                        xFace.setVisibleCameraId(3);
                        break;
                }
                xFace.reInitCaptor();
                addDialog.dismiss();
            });
            //设置红外摄像头id
            RadioGroup rgCameraInfrared = scrollView.findViewById(R.id.rg_camera_infrared);
            switch (xFace.getInfraredCameraId()){
                case 0 :
                    rgCameraInfrared.check(R.id.rb_camera_infrared_0);
                    break;
                case 1 :
                    rgCameraInfrared.check(R.id.rb_camera_infrared_1);
                    break;
                case 2 :
                    rgCameraInfrared.check(R.id.rb_camera_infrared_2);
                    break;
                case 3 :
                    rgCameraInfrared.check(R.id.rb_camera_infrared_3);
                    break;
            }
            rgCameraInfrared.setOnCheckedChangeListener((radioGroup, i) -> {
                switch (i){
                    case R.id.rb_camera_infrared_0:
                        xFace.setInfraredCameraId(0);
                        break;
                    case R.id.rb_camera_infrared_1:
                        xFace.setInfraredCameraId(1);
                        break;
                    case R.id.rb_camera_infrared_2:
                        xFace.setInfraredCameraId(2);
                        break;
                    case R.id.rb_camera_infrared_3:
                        xFace.setInfraredCameraId(3);
                        break;
                }

                xFace.reInitCaptor();
                addDialog.dismiss();
            });
            addDialog.setView(scrollView);
            addDialog.show();

        });
        btnRegister.setOnClickListener(view -> {
            showLoadingDialog();
            if( addDialog!=null && addDialog.isShowing()) addDialog.dismiss();
            addDialog = new AlertDialog.Builder(this)
                    .setNegativeButton("取消", (dialogInterface, i) -> {
                        dismissLoadingDialog();
                        addDialog.dismiss();
                    }).create();
            xFace.getCurrentFrame(frame -> {
                if(frame!=null){
                    LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(bContext).inflate(R.layout.dialog_register,null);
                    ImageView imgView = linearLayout.findViewById(R.id.iv);
                    TextView tvUserId = linearLayout.findViewById(R.id.tv_user_id);
                    TextView tvUserName = linearLayout.findViewById(R.id.tv_user_name);
                    imgView.setImageBitmap(BitmapFactory.decodeByteArray(frame, 0, frame.length));
                    imgView.setScaleX(-1);
                    List<Face> currentList = xFace.listAllFaces();
                    int minId = 0;
                    for(Face face : currentList){
                        try {
                            if(Integer.parseInt(face.getUserid())>minId){
                                minId = Integer.parseInt(face.getUserid());
                            }
                        }catch (Exception e){
                            continue;
                        }
                    }

                    //保存byte[]图片到本地
                    File faceFileDir = new File(IMG_PATH);
                    if (!faceFileDir.exists()){
                        try {
                            FileUtil.createDir(faceFileDir);
                        } catch (IOException e) {
                            e.printStackTrace();
                            dismissLoadingDialog();
                            return;
                        }
                    }
                    String userId = String.valueOf(minId+1);
                    String userName = "用户"+userId;
                    String faceFileName = new StringBuilder()
                            .append(IMG_PATH)
                            .append(userId)
                            .append("_")
                            .append(userName)
                            .append(".png")
                            .toString();
                    File faceFile = new File(faceFileName);
                    try {
                        FileUtil.writeByteToFile(faceFile,frame,false,true);
                    } catch (IOException e) {
                        e.printStackTrace();
                        dismissLoadingDialog();
                        return;
                    }


                    tvUserId.setText(userId);
                    tvUserName.setText(userName);
                    // 0:url
                    // 1:本地路径
                    // 2:base64
                    Face face = new Face()
                            .setRep(1)
                            .setUserid(userId)
                            .setUsername(userName)
                            .setFacetype(1)
                            .setFace(faceFileName);
                    dismissLoadingDialog();

                    addDialog.setButton(DialogInterface.BUTTON_POSITIVE, "注册", (dialogInterface, i) -> {
                        showLoadingDialog();
                        if( addDialog.isShowing()) addDialog.dismiss();
                        switch (xFace.addFace(frame,face)) {
                            case -1:
                                toast("图片人脸特征提取失败!");
                                break;
                            case -2:
                                toast("注册失败");
                                break;
                            default:
                                toast("注册成功");
                                break;
                        }
                        dismissLoadingDialog();
                    });
                    addDialog.setView(linearLayout);
                    addDialog.show();
                    addDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.GRAY);
                }
            });
        });

        btnQuery.setOnClickListener(view -> {
            showLoadingDialog();
            ListView listView = (ListView) getLayoutInflater().inflate(R.layout.dialog_query_list, null);
            List<Face> faces = new ArrayList<>();
            AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("人员列表"+"("+faces.size()+")")
                    .setView(listView)
                    .setPositiveButton("返回", (paramAnonymousDialogInterface, paramAnonymousInt) -> {

                    }).create();
            FaceQueryAdapter adapter = new FaceQueryAdapter(bContext, faces, xFace,alertDialog,captureConfig_1vn.getCaptureType());
            listView.setAdapter(adapter);
            xFace.listAllFacesAsync(faceList -> {
                faces.clear();
                faces.addAll(faceList);
                runOnUiThread(() -> {
                    adapter.notifyDataSetChanged();
                    alertDialog.setTitle("人员列表"+"("+faces.size()+")");
                    alertDialog.show();
                    dismissLoadingDialog();
                });
            });
        });
    }

    private int getDoubleArrayPosition(String[] array, double value) {
        int position = 0;
        for (int i = 0; i < array.length; i++) {
            if (Double.parseDouble(array[i]) == value) {
                position = i;
            }
        }
        return position;
    }
    private int getIntArrayPosition(String[] array, int value) {
        int position = 0;
        for (int i = 0; i < array.length; i++) {
            if (Integer.parseInt(array[i]) == value) {
                position = i;
            }
        }
        return position;
    }


    private void startUp() {
        tvInit.setText("初始化...");
        if(!checkPermission()){
            ActivityCompat.requestPermissions(this, requestPermissions.toArray(new String[requestPermissions.size()]), REQUEST_CODE);
        }else{
            //加载算法
            xFace = XFace.getInstance(bContext)
                    .setCaptureListener(this)//必须
                    .setFaceAccessListener(this)//必须
                    .setSurfaceInfrared(findViewById(R.id.infrared_camera))//双目必须
                    .setSurfaceVisible(findViewById(R.id.visible_camera))//必须
                    .setInitListener(this)//必须
                    .setVideo_width(VIDEO_WIDTH)//必须
                    .setVideo_height(VIDEO_HEIGHT)//必须
                    .setUseDualCamera(captureConfig_1vn.isUseDualCamera())//是否双目，可选，默认双目true
                    .setCaptureSecureLevel(captureConfig_1vn.getCaptureSecureLevel())//活体安全等级0~3
                    .setMinFaceRatio(captureConfig_1vn.getMinFaceRatio())//最小人脸比率
                    .setVisibleCameraId(captureConfig_1vn.getVisibleCameraId())//必填默认为0
                    .setInfraredCameraId(captureConfig_1vn.getInfraredCameraId())//双目必填默认为1
                    .setCameraDegree(captureConfig_1vn.getCameraDegree())//相机角度
                    .setFrameDataDegree(captureConfig_1vn.getFrameDataDegree())//帧数据内容角度
                    .setCaptureType(captureConfig_1vn.getCaptureType())//必填 0:1v1 , 1:1vduin , 2:nvn
                    .setVerifyInstanceNum(captureConfig_1vn.getVerifyInstanceNum())
                    .setNeedAutoFocus(captureConfig_1vn.isNeedAutoFocus())
                    .setActivateCode(this.activateCode)//线下向商务申请
                    .setEnableWatchDog(true)
                    .setAutoRecovery(true)
                    .setWatchDogListener(this)
                    .init();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    // 申请权限相关
    private static String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
    };
    //检查权限
    private boolean checkPermission() {

        boolean flag = true;
        requestPermissions = new ArrayList<>();

        if (ContextCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_DENIED) {
            requestPermissions.add(permissions[0]);
            flag = false;
            toast("请打开存储读写权限，确保APP正常运行");
        }
        if (ContextCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_DENIED) {
            requestPermissions.add(permissions[1]);
            flag = false;
            toast("请打开存储读写权限，确保APP正常运行");
        }
        if (ContextCompat.checkSelfPermission(this, permissions[2]) == PackageManager.PERMISSION_DENIED) {
            requestPermissions.add(permissions[2]);
            flag = false;
            toast("没有摄像头权限我什么都做不了哦!");
        }
        return flag;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean isGranted = true;
        try {
            switch (requestCode) {
                case REQUEST_CODE:
                    for (int i : grantResults) {
                        if (i == PackageManager.PERMISSION_DENIED) {
                            toast("请授予相应权限，确保APP正常运行");
                            isGranted = false;
                            break;
                        }
                    }
                    break;
            }
            if (isGranted) {
                startUp();
            }
        } catch (Exception e) {
            LogUtil.e(TAG, "Failed to request Permission", e);
        }
    }


    @Override
    public void onInit(int rtn,String message) {
        switch (rtn){
            case ERROR_SUCCESS:
                toast("初始化成功!");
                LogUtil.e(TAG,"startUp Success");
                tvInit.setText("初始化成功!");
                tvInit.setVisibility(View.GONE);
                initOverlay();
                break;
            case ERROR_SUCCESS_CAMERA://摄像头初始化成功
                initOverlay();
            case ERROR_PROCESSING:
                LogUtil.e(TAG,"startUp-->"+message);
                tvInit.setText(message);
                break;
            default:
                toast("初始化失败("+rtn+"):"+message);
                tvInit.setText("初始化失败("+rtn+")\n"+message);
                LogUtil.e(TAG,"startUp Fail-->"+rtn+"-->"+message);
                break;
        }
    }

    //初始化绘制人脸框VIEW
    private void initOverlay() {
        ((CameraDetectView)overlayView).init(VIDEO_WIDTH, VIDEO_HEIGHT,height,width,captureConfig_1vn.getScaleX());
    }


    @Override
    public void onCapture(List<FaceEntity> faceEntityList) {
        List<OverlayEntity> overlayEntityList = new ArrayList<>();
        for(FaceEntity faceEntity :faceEntityList){
            OverlayEntity overlayEntity = new OverlayEntity();
            overlayEntity.setRect(faceEntity.getVisibleFaceRect());
            //绘制人脸框
            int paintColor;
            switch (faceEntity.getSessionStatus()){
                case SESSION_PASS:
                case SESSION_SINGLE_FRAME_OK:
                    paintColor = PAINT_COLOR_FACE_PASS;
                    break;
                default:
                    paintColor = PAINT_COLOR_FACE;
            }
            overlayEntity.setPaintColor(paintColor);
            overlayEntityList.add(overlayEntity );
            runOnUiThread(() -> {
                        if(faceEntity.getSessionStatus()!=SESSION_PASS)tvTitle.setText(faceEntity.getSessionTitle());
                    }
            );
        }
//        LogUtil.e(TAG, Arrays.toString(faceEntityList.toArray()));
        ((CameraDetectView)overlayView).setValue(overlayEntityList);
        overlayView.postInvalidate();
    }

    @Override
    public void onFace(List<Face> faceList, long spend) {
        if(faceList.size()>0){
            StringBuilder stringBuilder = new StringBuilder();
            for (Face face :
                    faceList) {
                stringBuilder
                        .append(face.getUserid())
                        .append("_")
                        .append(face.getUsername())
                        .append("_").append(face.getSimilarity())
                        .append("%")
                        .append(" ");
            }
            if(stringBuilder.length()>0) {
                stringBuilder.append(spend).append("ms");
                runOnUiThread(() -> tvResult.setText(stringBuilder.toString()));
                faceQueryHandler.removeCallbacks(faceQueryRunnable);
                faceQueryHandler.postDelayed(faceQueryRunnable, 650);
            }
        }
    }

    @Override
    public void onDogEvent(WatchDogEvent watchDogEvent) {
        LogUtil.e(TAG,watchDogEvent.toString());
    }
}
